package org.jeecg.modules.complain.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonDefine;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.sms.SmsUtil;
import org.jeecg.modules.complain.entity.*;
import org.jeecg.modules.complain.service.*;
import org.jeecg.modules.system.entity.SmsEntity;
import org.jeecg.modules.system.entity.SysDepartPosition;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserPosition;
import org.jeecg.modules.system.service.ISysPositionService;
import org.jeecg.modules.system.service.ISysUserPositionService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
* @Description: 报修处理APP端接口
* @Author: jeecg-boot
* @Date:   2019-08-04
* @Version: V1.0
*/
@Slf4j
@Api(tags="报修处理")
@RestController
@RequestMapping("/b/app/repair")
public class RepairAppController {
   @Autowired
   private IRepairService repairService;
   @Autowired
   private IRepairConfigService repairConfigService;
   @Autowired
   private IPrjBtnService prjBtnService;
   @Autowired
   private IRepairStatusService repairStatusService;
   @Autowired
   private IRepairChargeService repairChargeService;
   @Autowired
   private ISysUserService sysUserService;
   @Autowired
   private ISysUserPositionService sysUserPositionService;
   @Autowired
   private ISysPositionService sysPositionService;

   private static long seq = 0;
   private static String  templateCode ="SMS_142951838";
   /**
     *  编辑
    * @param repair
    * @return
    */
   @AutoLog(value = "报修处理-编辑")
   @ApiOperation(value="报修处理-编辑", notes="报修处理-编辑")
   @PutMapping(value = "/edit")
   public Result<Repair> edit(@RequestBody Repair repair) {
       Result<Repair> result = new Result<Repair>();
       Repair repairEntity = repairService.getById(repair.getId());
       if(repairEntity==null) {
           result.error500("未找到对应实体");
       }else {
           boolean ok = repairService.updateById(repair);
           //TODO 返回false说明什么？
           if(ok) {
               result.success("修改成功!");
           }
       }

       return result;
   }




     /**
     * 报修单列表()
     * @param userId
     * @param status
     */

    @RequestMapping("getHandDetail")
    public Result<List<Repair>> getHandDetail(@RequestParam(name = "userId")String userId,
                                              @RequestParam(name = "status")Integer status,
                                              @RequestParam(name = "departId")String departId){

        Result<List<Repair>> result = new Result<>();
        List<SysDepartPosition> sysDepartPositionList = sysUserPositionService.selectPositionId(userId);
        //获取该人员所有部门
        if (sysDepartPositionList.size() <=  0){
            result.setMessage("没有结果");
            result.setSuccess(true);
            return result;
        }
        //获取所有管理处配置

        List<RepairConfig> repairConfigList = repairConfigService.selectAllRepairConfig(sysDepartPositionList);
        if (repairConfigList.size() <= 0 ){
            result.setMessage("请配置管理处处理配置");
            result.setSuccess(true);
            return result;
        }

        List< Repair> AllRepairResult = new ArrayList<>();
        for (RepairConfig repairConfig:repairConfigList) {
            ArrayList<String> positionIdList = new ArrayList<>();
            for (SysDepartPosition sysDepartPosition:sysDepartPositionList) {
                if (repairConfig.getDepartId().equals(sysDepartPosition.getOfficeId())){
                    positionIdList.add(sysDepartPosition.getPositionId());
                }
            }
            List<String> reciveIdList = Arrays.asList(repairConfig.getReceivePositionCode().split(","));
            List<Repair> repairsList = repairStatusService.selectByUserId(userId, status,repairConfig.getDepartId(),reciveIdList,positionIdList);
               if (repairsList.size()>0){
            AllRepairResult.addAll(repairsList);
               break;
               }

        }
        result.setMessage("成功");
        result.setSuccess(true);
        result.setResult(AllRepairResult);
        return result;
    }
    /**
     * 客服经理指派
     *
     */
    @RequestMapping("repairHandle")
    public Result<?> repairHandle(RepairStatus repairStatus){

        Result<Object> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
        RepairStatus repair = repairStatusService.selectByRepairId(repairStatus.getRepairId(),CommonDefine.REPAIR_STATUS_200);
        if (repair != null){
            return Result.error("该维修单已经指派给维修人员");
        }
        Integer integer = repairService.updateRepairStatus(repairStatus.getRepairId(),CommonDefine.REPAIR_STATUS_200);
        //存入维修状态表 报修受理状态
        repairStatus.setCreateTime(new Date());
        repairStatus.setStatus(CommonDefine.REPAIR_STATUS_200);
        repairStatus.setReturnRepair(null);
        repairStatusService.delete(repairStatus.getRepairId(),CommonDefine.REPAIR_STATUS_100);
        boolean falg = repairStatusService.save(repairStatus);
        //推送
        SmsEntity smsEntity = SmsUtil.sendSms(repairStatus.getMobile(), templateCode, "community", repairStatus.getProjectName(), "username", repairStatus.getRealName(), "number", repairStatus.getPhone());
        if (falg && integer>0){
            return Result.ok("受理成功");
        }
        return  result;
    }
    /**
     * To deal with Repair
     * @param: repairId
     */
    @RequestMapping("orderReceive")
    public Result<?> orderReceive(@RequestParam(name = "repairId")String repairId,
                                  @RequestParam(name = "userId")String userId,
                                  @RequestParam(name = "status")Integer status,
                                  @RequestParam(name = "beforePicture")String beforePicture){
         Result<Object> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
         //查询该订单有没有被人接单
         RepairStatus repairStatus = new RepairStatus();
         if (status == CommonDefine.REPAIR_STATUS_100){
            //客服直接去处理
             RepairStatus repairStatus1 = repairStatusService.selectByRepairId(repairId, CommonDefine.REPAIR_STATUS_100);
             if (repairStatus1 == null){
                result.setMessage("操作错误");
                result.setSuccess(false);
                return result;
            }
            Repair repair = repairService.selectByIds(repairId);
            if (repair != null){
                repairStatus.setRepairId(repair.getId());
                repairStatus.setCreateTime(new Date());
                repairStatus.setStatus(CommonDefine.REPAIR_STATUS_300);
                repairStatus.setId(null);
                SysUser sysUser = sysUserService.getById(userId);
                repairStatus.setMobile(sysUser.getPhone());
                repairStatus.setUserName(sysUser.getRealname());
                repairStatus.setUserId(sysUser.getId());
                repairStatus.setBeforePicture(beforePicture);
                repairStatusService.delete(repairId,CommonDefine.COMPLAIN_STATUS_100);
            }
         }else if (status == CommonDefine.REPAIR_STATUS_200){//已指派维修工去处理
            RepairStatus rp = repairStatusService.selectByRepairId(repairId, CommonDefine.REPAIR_STATUS_300);
            if (rp != null){
                result.setMessage("该维修单已被接单");
                result.setSuccess(false);
                return result;
            }
            repairStatus = repairStatusService.selectByRepairId(repairId, CommonDefine.REPAIR_STATUS_200);
            repairStatus.setCreateTime(new Date());
            repairStatus.setStatus(CommonDefine.REPAIR_STATUS_300);
            repairStatus.setId(null);
            repairStatus.setBeforePicture(beforePicture);
            repairStatusService.delete(repairId,CommonDefine.REPAIR_STATUS_200);
         }else{
             result.setMessage("该维修单不可进行此操作");
             result.setSuccess(false);
            return result;
         }
            repairService.updateRepairStatus(repairId,CommonDefine.REPAIR_STATUS_300);
            repairStatusService.save(repairStatus);
            return result;
     }
    /**
     * 挂起状态
     * @Param repairId
     * @Param Contents
     */
    @RequestMapping("repairHandUp")
    public Result<?> repairHandUp(@RequestParam(name = "repairId")String repairId,
                                  @RequestParam(name = "content")String contents
                                  ){
        Result<Object> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
        RepairStatus repairStatus = repairStatusService.selectByRepairId(repairId,CommonDefine.REPAIR_STATUS_300);
        if (null == repairStatus){
            return  Result.error("该维修单没有开始维修无法挂起");
        }
        repairStatus.setStatus(CommonDefine.REPAIR_STATUS_500);
        repairStatus.setContents(contents);
        repairStatus.setCreateTime(new Date());
        repairStatus.setId(null);
        repairStatusService.delete(repairId,CommonDefine.REPAIR_STATUS_300);
        repairStatusService.save(repairStatus);
        //报修状态改为挂起
        Integer integer = repairService.updateRepairStatus(repairId, CommonDefine.REPAIR_STATUS_500);
        result.setSuccess(integer>0);
        return result;
    }
    /**
     * 挂起继续完成工单
     * @Param repairId
     */
    @RequestMapping("hangUpComplete")
    public Result<?> hangUpComplete(@RequestParam(name = "repairId")String repairId){
        Result<Object> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
        RepairStatus repairStatus = repairStatusService.selectByRepairId(repairId, CommonDefine.REPAIR_STATUS_500);
        if (null == repairStatus ){
            return Result.error("该维修单不在挂起中无法继续维修");
        }
         repairStatus.setCreateTime(new Date());
         repairStatus.setStatus(CommonDefine.REPAIR_STATUS_300);
         repairStatus.setId(null);
         repairStatusService.save(repairStatus);
         repairStatusService.delete(repairId,CommonDefine.REPAIR_STATUS_500);
         Integer integer = repairService.updateRepairStatus(repairId, CommonDefine.REPAIR_STATUS_300);
         result.setSuccess(integer>0);
         return result;
    }


    /**
     * complete Repair
     * @Param repairId
     */
    @RequestMapping("completeRepair")
    public Result<?> completeRepair(@RequestParam(name = "repairId")String repairId,
                                    @RequestParam(name = "attachFile") String attachFile,
                                    @RequestParam(name = "contents")String contents,
                                    @RequestParam(name = "confirmPay")Integer confirmPay,
                                    Double repairMaterialFee,Double repairManHourfee)   {
        Result<Object> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
        RepairStatus repairStatus = repairStatusService.selectByRepairId(repairId,CommonDefine.REPAIR_STATUS_300);
        if (null == repairStatus ){
            return  Result.error("该维修单没有开始维修无法完成");
        }
        repairStatusService.delete(repairId,CommonDefine.REPAIR_STATUS_300);
        repairStatus.setStatus(CommonDefine.REPAIR_STATUS_600);
        repairStatus.setContents(contents);
        repairStatus.setId(null);
        repairStatus.setCreateTime(new Date());
        RepairCharge repairCharge = new RepairCharge();
        repairStatus.setAttachFile(attachFile);
        String repairNo = DateUtils.getDate("yyyyMMddHHmmss") + String.format("%06d", seq++);
        if(seq > 999999){
            seq = 0;
        }
        repairCharge.setRepairNo(repairNo);
        if (confirmPay == CommonDefine.ConfirmPay.CONFIRM_PAY_0){
            repairStatus.setConfirmPay(CommonDefine.ConfirmPay.CONFIRM_PAY_0);
            repairCharge.setRepairManHourfee(repairManHourfee);
            repairCharge.setRepairMaterialFee(repairMaterialFee);
            repairCharge.setRepairId(repairId);
            repairCharge.setCreateTime(new Date());
            BigDecimal bigDecimal = new BigDecimal(repairManHourfee.toString());
            BigDecimal bigDecimal1 = new BigDecimal(repairMaterialFee.toString());
            double v = bigDecimal.add(bigDecimal1).doubleValue();
            repairCharge.setAmount(v);
            Repair repair = repairService.selectByIds(repairId);
            repairCharge.setRoomId(repair.getRoomId());
            repairCharge.setIsPay(0);
            repairCharge.setPayPhone(repair.getMobile());
            repairChargeService.save(repairCharge);
            //查询房间ID
            result.setResult(repairCharge);
        }else {
            repairStatus.setConfirmPay(CommonDefine.ConfirmPay.CONFIRM_PAY_1);
            repairCharge.setRepairManHourfee(repairManHourfee);
            repairCharge.setRepairMaterialFee(repairMaterialFee);
            repairCharge.setRepairId(repairId);
            repairCharge.setCreateTime(new Date());
            repairCharge.setIsPay(0);
            repairChargeService.save(repairCharge);
        }
        repairStatusService.save(repairStatus);
        Integer integer = repairService.updateRepairStatus(repairId, CommonDefine.REPAIR_STATUS_600);
        result.setSuccess(integer>0);
        return result;
    }
    /**
     * Close Repair(handle User)
     * param:repairId
     */
    @RequestMapping("closeRepair")
    public Result<?> closeRepair(@RequestParam(name = "repairId")String repairId,
                                 @RequestParam(name = "contents")String contents,
                                 @RequestParam(name = "status")Integer status){
          Result<Object> result = new Result<>();
         LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
           //挂起状态关闭维修单
          RepairStatus repairStatus;
          if (status == CommonDefine.REPAIR_STATUS_500){
             repairStatus = repairStatusService.selectByRepairId(repairId, CommonDefine.REPAIR_STATUS_500);
             if (repairStatus == null){
                 return Result.error("该工单没有挂起");
             }
             repairStatus.setStatus(CommonDefine.REPAIR_STATUS_800);
             repairStatus.setCreateTime(new Date());
             repairStatus.setContents(contents);
             repairStatus.setId(null);
             repairStatusService.delete(repairId,CommonDefine.REPAIR_STATUS_500);
             repairStatusService.save(repairStatus);
             Integer integer = repairService.updateRepairStatus(repairId, CommonDefine.REPAIR_STATUS_800);
             result.setSuccess(integer>0);
             }else  if (status == CommonDefine.REPAIR_STATUS_300){
             repairStatus = repairStatusService.selectByRepairId(repairId, CommonDefine.REPAIR_STATUS_300);
             if (repairStatus == null){
                 return Result.error("该工单没有开始维修");
             }
             repairStatus.setCreateTime(new Date());
             repairStatus.setContents(contents);
             repairStatus.setId(null);
             repairStatus.setStatus(CommonDefine.REPAIR_STATUS_800);
             repairStatusService.delete(repairId,CommonDefine.REPAIR_STATUS_300);
             repairStatusService.save(repairStatus);
             Integer integer = repairService.updateRepairStatus(repairId, CommonDefine.REPAIR_STATUS_800);
             result.setSuccess(integer>0);
         }else{
             return Result.error("该状态不支持此操作");
         }
         return  result;
    }
    /**
     * Repair Status Process()
     * @param repairId
     */
    @RequestMapping("getRepairAllStatus")
    public Result<List<RepairStatus>> getRepairAllStatus(@RequestParam(name = "repairId")String repairId){
        Result<List<RepairStatus>> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
        List<RepairStatus> repairStatuses = repairStatusService.selectRepairStatus(repairId);
        for (RepairStatus rs: repairStatuses){
            if (rs.getStatus()==CommonDefine.REPAIR_STATUS_100){
                rs.setUserName(rs.getCreateBy());
            }
        }
        result.setResult(repairStatuses);
        return  result;
    }
    /**
     * App btn Control
     */
    @RequestMapping("controlBtn")
    public Result<PrjBtn> controlBtn(@RequestParam(name = "userId")String userId){
        Result<PrjBtn> result = new Result<>();
        PrjBtn prjBtn ;
          prjBtn = prjBtnService.selectControlByuserId(userId);
        if (prjBtn != null){
            result.setResult(prjBtn);
        }
        result.setResult(prjBtn);
        return result;
    }
    /**
     * App Position  User
     * @Param departId
     */
    @RequestMapping("getAllPostionUser")
    public Result<List<SysUserPosition> > getAllPostionUser(@RequestParam(name = "departId")String departId,
                                                            @RequestParam(name = "userId")String userId){
       Result<List<SysUserPosition> > result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
       //该departId为报修单所在管理处ID
       RepairConfig repairConfig = repairConfigService.selectConfigByDepartId(departId);
        if (repairConfig == null){
            return Result.error("该管理处没有报修配置");
        }
        //拿到该管理处可维修人员的配置
        String handlePositionCode = repairConfig.getHandlePositionCode();
        List<String> codeList = Arrays.asList(handlePositionCode.split(","));
        List<SysUserPosition> allPositionUser = repairConfigService.getAllPostionUser(departId,codeList,userId);
        result.setResult(allPositionUser);
        return result;
    }
    /**
     * RepairDetail
     * repairId
     */
    @RequestMapping("repairDetail")
    public Result<Repair> repairDetail(@RequestParam(name = "repairId")String repairId, @RequestParam(name = "userId") String userId){
        Result<Repair> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
        Repair repair = repairService.selectRepairDetail(repairId);
        String roomInfo = repairService.findRoomInfo(repair.getRoomId());
        List<RepairStatus> repairStatuses = repairStatusService.selectRepairStatus(repairId);
        repair.setRepairStatusList(repairStatuses);
        repair.setRoomInfo(roomInfo);
        result.setResult(repair);
        return  result;
    }
   /* *//**
     * image upload
     * @param request
     * @param files
     * @return String
     * @throws IOException
     *//*
    @RequestMapping("uploadFile")
    public Result<String> uploadImageNew(HttpServletRequest request, MultipartFile[] files) throws IOException {
         Result<String> result = new Result<>();
         String imageStr = "";
         for (MultipartFile file : files){
            // 上传图片的原始名称
            String originalFilename = file.getOriginalFilename();
            String key = "pic/";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String ymd = sdf.format(new Date());
            // 新的图片名称(真实名称)
            String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 新图片的路径
            key += ymd + "/" + newFileName;
            Boolean pic_flg = AliyunOssHelper.put(key, file.getInputStream());
            if (pic_flg) {
                imageStr = imageStr + AliyunOssHelper.getUrlPath(key) + ";";
            } else {
                result.setMessage("出错了");
                return result;
            }
        }
        imageStr = imageStr.substring(0, imageStr.length() - 1);
        result.setResult(imageStr);
        result.setMessage("图片上传成功！");
        return result;
    }*/
    /**
     * 维修工驳回
     *
     */
    @RequestMapping("returnRepair")
    public Result<?> returnRepair(RepairStatus repairStatus){
        Result<Object> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
        if (StringUtils.isEmpty(repairStatus.getContents())){
            return Result.error("请填写驳回理由");
        }
        RepairStatus rps = repairStatusService.selectByRepairId(repairStatus.getRepairId(), CommonDefine.REPAIR_STATUS_200);
        if ( null == rps ){
            return Result.error("操作错误，请联系管理员");
        }
        repairStatus.setReturnRepair(1);
        Integer integer = repairStatusService.returnRepair(repairStatus);
        result.setSuccess(integer > 0);
        return result;
    }

    /**
     * 维修工单角标/红点
     * @param userId
     * @return
     */
    @RequestMapping("statisticsRepair")
    public Result<?> statisticsRepair(@RequestParam (value = "userId") String userId, @RequestParam (value = "departId") String departId){
        Result<Object> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        if (loginUser == null || StringUtils.isEmpty(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
        try {
            Map<String, Integer> map = new HashMap<>();
            //查询人部门的管理处ID
            String officeId = repairConfigService.selectDepartId(departId);
            //查询该人员的岗位
            List<String> positionIdList = sysUserPositionService.queryPositionId(userId,officeId);
            //查询管理处配置接受岗位
            RepairConfig repairConfig = repairConfigService.selectConfigByDepartId(officeId);
            if ( positionIdList.size() <= 0 || null == repairConfig){
                map.put("status_200", 0);
            }else {
                List<String> reciveIdList = Arrays.asList(repairConfig.getReceivePositionCode().split(","));
                List<Repair> repairsList = repairStatusService.selectByUserId(userId, CommonDefine.REPAIR_STATUS_200,officeId,reciveIdList,positionIdList);
                map.put("status_200", repairsList.size());
            }
            map.put("status_300", repairStatusService.statisticsRepair(userId, CommonDefine.REPAIR_STATUS_300));
            map.put("status_600", repairStatusService.statisticsRepair(userId, CommonDefine.REPAIR_STATUS_600));
            map.put("status_800", repairStatusService.statisticsRepair(userId, CommonDefine.REPAIR_STATUS_800));
            map.put("status_900", repairStatusService.statisticsRepair(userId, CommonDefine.REPAIR_STATUS_900));
            result.setResult(map);
        }catch (Exception ex){
            result.error500("查询失败！");
        }
        return result;
    }
}





